from tortoise import fields
from tortoise.models import Model
from tortoise.validators import MinValueValidator

class WarehouseGoods(Model):
    """仓库商品关系模型"""
    
    id = fields.IntField(pk=True)
    warehouse = fields.ForeignKeyField(
        'models.Warehouse', 
        related_name='goods_relations',
        description='仓库ID',
        on_delete=fields.CASCADE
    )
    goods = fields.ForeignKeyField(
        'models.Goods', 
        related_name='warehouse_relations',
        description='商品ID',
        on_delete=fields.CASCADE
    )
    quantity = fields.IntField(
        default=0, 
        description='当前库存数量',
        validators=[MinValueValidator(0)]
    )
    min_quantity = fields.IntField(
        default=0, 
        description='最小库存',
        validators=[MinValueValidator(0)]
    )
    max_quantity = fields.IntField(
        default=0, 
        description='最大库存',
        validators=[MinValueValidator(0)]
    )
    create_at = fields.DatetimeField(auto_now_add=True, description='创建时间')
    update_at = fields.DatetimeField(auto_now=True, description='更新时间')

    class Meta:
        table = "warehouse_goods"
        table_description = "仓库商品关系表"
        unique_together = (("warehouse", "goods"),)

    def __str__(self):
        return f"Warehouse {self.warehouse_id} - Goods {self.goods_id}"

    async def validate_quantities(self):
        """验证库存数量的合法性"""
        if self.max_quantity < self.min_quantity:
            raise ValueError("最大库存不能小于最小库存")
        if self.quantity < 0:
            raise ValueError("库存数量不能为负数")
        if self.quantity > self.max_quantity:
            raise ValueError("库存数量不能超过最大库存")